package com.site.utils;

import org.noear.esearchx.EsContext;
import org.noear.esearchx.model.EsData;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Result;

import java.io.IOException;

@Component
public class EsUtils {

    @Inject("${url.es}")
    EsContext esx;

    public Result<EsData<ONode>> getAll(String index) {
        try {
            EsData<ONode> result = esx.indice(index)
                    .selectList(ONode.class);
            return Result.succeed(result);
        } catch (IOException e) {
            return Result.failure();
        }

    }

    public <T> Result<T> page(String index, IPage page) {
        return null;
    }

    public Result<ONode> get(String index, String id) {
        try {
            ONode result = esx.indice(index).selectById(ONode.class, id);
            return Result.succeed(result);
        } catch (IOException e) {
            return Result.failure();
        }
    }

    public Result<String> add(String index, ONode node) {
        try {
            esx.indice(index).insert(node);
            return Result.succeed();
        } catch (IOException e) {
            return Result.failure();
        }
    }

    public Result<String> put(String index, ONode node) {
        try {
            String id = node.get("id").toString();
            esx.indice(index).upsert(id, node);
            return Result.succeed();
        } catch (IOException e) {
            return Result.failure();
        }
    }

    public Result<String> delete(String index, String id) {
        try {
            esx.indice(index).deleteById(id);
            return Result.succeed();
        } catch (IOException e) {
            return Result.failure();
        }
    }
}
